package com.lzy.chat.f_config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {


    //不注册这个在过滤器中 service将报空
    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }

    @Bean
    public CurrentUserHandlerMethodArgResolver currentUserHandlerMethodArgResolver() {
        return new CurrentUserHandlerMethodArgResolver();
    }

    //添加@CurrentUser注解的实现类
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(currentUserHandlerMethodArgResolver());
    }

    //添加拦截器方法
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        //添加拦截路径
        String[] addPathPatters = {
                "/**"
        };
        //添加不拦截路径
        String[] excludePathPatters = {
                "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg",
                "/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg",
                "/**/*.ttf", "/**/*.woff", "/**/*.eot", "/**/*.otf", "/**/*.woff2",
                "/images/**"
        };
        //注册登录拦截器
        registry.addInterceptor(loginInterceptor()).addPathPatterns(addPathPatters).excludePathPatterns(excludePathPatters);
        //如果多条拦截器则增加多条
    }

    @Value("${file-save-path}")
    private String fileSavePath;

    //添加放行静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //文件磁盘图片url 映射
        //配置server虚拟路径，handler为前台访问的目录，locations为files相对应的本地路径
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + fileSavePath);
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

    //跨域设置
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }


}
